package network2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoSever2 {
    private DatagramSocket packet=null;
    public UdpEchoSever2(int port){
        try {
            packet=new DatagramSocket(port);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }
    public void start(){
        while(true){
            System.out.println("服务器启动");
            DatagramPacket respPacket=new DatagramPacket(new byte[4096],4096);
            try {
                packet.receive(respPacket);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String  resp=new String(respPacket.getData(),0,respPacket.getLength());
            String respon=process(resp);
            DatagramPacket responPacket=new DatagramPacket(respon.getBytes(),respon.getBytes().length,respPacket.getSocketAddress());
            try {
                packet.send(responPacket);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            System.out.println("[%s:%d] resp=%s respon=%s",respPacket.getSocketAddress(),responPacket.getPort(),resp,respon);
        }
    }

    private String process(String resp) {
        return resp;
    }
}
